import React, { Component } from 'react'
import { View, Text, FlatList, Button } from 'react-native'


export default class MyList extends React.Component{
  constructor(props){
    super(props);
    this.state={
      datas: [{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'b'},{key: 'a'},{key: 'b'},{key: 'a'},{key: 'b'}],
    }
  }
  itemSepaComponent() {
    return (<View style={{height: 1,backgroundColor:'red'}}></View>)
  }
  emptyComponent() {
    return (
      <View style={{backgroundColor:'red',height: 500,alignItems:'center',justifyContent:'center'}}>
        <Text>list为空</Text>
      </View>
    )
  }
  headerfooterComponent(x){
    let i = x === 1?'我是头部111111':'我是尾部222222'
    return (
      this.state.datas.length !== 0?<View style={{alignItems:'center',backgroundColor:'green'}}><Text>{i}</Text></View>:null
    )
  }
  // 下拉刷新后所执行的函数
  refreshFlat() {
      this.setState({
        datas: [] // 这里将列表数据置空后，然而刷新后，datas已经为空了，页面渲染上还存在，但是头部组建与尾部组件为空了。
      })
  }
  render() {
    return (
      <View style={{flex:1}}>
        <Button title='滚动到指定位置' onPress={() =>{this.refs._flatList.scrollToOffset({animated: true, offset: 2000});}} /> 
        <View style={{flex:1}}>
          <FlatList 
            ref={'_flatList'}
            // ref={(flatList)=>this._flatList = flatList}
            ItemSeparatorComponent={this.itemSepaComponent}
            // horizontal={true}
            data={this.state.datas}
            renderItem={({item}) => <Text>{item.key}</Text>}
            ListEmptyComponent={this.emptyComponent()}
            ListHeaderComponent={() =>this.headerfooterComponent(1)}
            ListFooterComponent={() => this.headerfooterComponent(2)}
            extraData={this.state}
            onRefresh={() => this.refreshFlat()}
            refreshing={false}

            // getItemLayout={(data, index) => ({length:200,offset:(200+1)*index, index})}
          />
        </View>
      </View>
    )
  }
}
